<?php
/**
 * 采购计划下单->生成采购单
 */
namespace App\Admin\Controllers\Purchase;

use App\Jobs\Purchase\CreatePurchase;
use App\Models\Stocking\StockingApplyDetail;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Request;
class PlanConfirmController extends AdminController{

    protected $title = '采购单确认';

    public function confirm(Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['index'] ?? trans('admin.list'))
            ->body($this->form());
    }

    protected function form()
    {
        $pSkuIds = explode(',',Request::get('ids'));
        $res = StockingApplyDetail::query()
            ->whereIn('s_stocking_apply_detail.psku_id',$pSkuIds)
            ->where('s_stocking_apply_detail.plan_status','<>',3) //备货申请明细：3=》完全计划
            ->where('s_stocking_apply_detail.status',1) //备货申请明细：1=》已审核
            ->where('product_supplier.status',1) //产品供应商：1=》默认
            ->join('b_sys_area','b_sys_area.id','=','s_stocking_apply_detail.area_id')
            ->join('product_sku','product_sku.id','=','s_stocking_apply_detail.psku_id')
            ->leftJoin('product_supplier','product_supplier.psku_id','=','product_sku.id')
            ->select('s_stocking_apply_detail.*','b_sys_area.area','product_sku.psku_code','product_sku.psku_cn','product_supplier.supplier_id')
            ->get();
        $data = [];
        foreach ($res as $re){
            $temp = [];
            $temp['stocking_no'] = $re->stocking_no;
            $temp['area'] = $re->area;
            $temp['apply_detail_num'] = $re->apply_detail_num;
            $temp['plan_num'] = $re->plan_num;
            $temp['created_at'] = $re->created_at;
            $data[$re->psku_id]['detail'][$re->id] = $temp;
            if(isset($data[$re->psku_id]['apply_detail_num'])){
                $data[$re->psku_id]['apply_detail_num'] += $re->apply_detail_num;
            }else{
                $data[$re->psku_id]['apply_detail_num'] = $re->apply_detail_num;
            }
            if(isset($data[$re->psku_id]['plan_num'])){
                $data[$re->psku_id]['plan_num'] += $re->plan_num;
            }else{
                $data[$re->psku_id]['plan_num'] = $re->plan_num;
            }
            if(!isset($data[$re->psku_id]['psku_code'])){
                $data[$re->psku_id]['psku_code'] = $re->psku_code;
            }
            if(!isset($data[$re->psku_id]['psku_cn'])){
                $data[$re->psku_id]['psku_cn'] = $re->psku_cn;
            }
            if(!isset($data[$re->psku_id]['supplier_id'])){
                $data[$re->psku_id]['supplier_id'] = $re->supplier_id;
            }
        }
        return view('purchase.plan-confirm.index', compact('data'));
    }

    /**
     * 采购计划
     * @return \Illuminate\Http\JsonResponse
     */
    public function exePlan(){
        $param = Request::get('param');
        $data = [];
        foreach ($param as $_param){
            $pSkuId = $_param['psku_id'];
            $supplierId = $_param['supplier_id'];
            $applyDetailTotal = $_param['apply_detail_total'];
            if($applyDetailTotal == 0)continue;
            $thisPlanNum = $_param['this_plan_num'];
            if($thisPlanNum == 0)continue;
            $plannedNumTotal = $_param['planned_num_total'];
            $applyDetail = $_param['apply_detail'];
            $planNumTotal = $thisPlanNum + $plannedNumTotal;
            if($applyDetailTotal == $planNumTotal){
                foreach ($applyDetail as $_applyDetail){
                    list($applyDetailId,$applyDetailNum,$plannedNum) = explode("_",$_applyDetail);
                    $data[$supplierId][$pSkuId][$applyDetailId]['plan_num'] = $applyDetailNum - $plannedNum;
                    $data[$supplierId][$pSkuId][$applyDetailId]['apply_num'] = $applyDetailNum;
                }
            }else{
                $count = count($applyDetail);
                $surplus = $i = 0;
                if($applyDetailTotal < $planNumTotal){
                    foreach ($applyDetail as $_applyDetail){
                        list($applyDetailId,$applyDetailNum,$plannedNum) = explode("_",$_applyDetail);
                        $data[$supplierId][$pSkuId][$applyDetailId]['plan_num'] = $applyDetailNum - $plannedNum;
                        $data[$supplierId][$pSkuId][$applyDetailId]['apply_num'] = $applyDetailNum;
                    }
                    $thisPlanNumTemp = $planNumTotal - $applyDetailTotal;
                    foreach ($applyDetail as $_applyDetail){
                        list($applyDetailId,$applyDetailNum,$plannedNum) = explode("_",$_applyDetail);
                        $i++;
                        if($i == $count){
                            $_thisPlanNum = $thisPlanNumTemp - $surplus;
                        }else{
                            $_thisPlanNum = (int)floor($applyDetailNum / $applyDetailTotal * $thisPlanNumTemp);
                            $surplus += $_thisPlanNum;
                        }
                        if($_thisPlanNum == 0)continue;
                        $data[$supplierId][$pSkuId][$applyDetailId]['plan_num'] += $_thisPlanNum;
                    }
                }else{
                    foreach ($applyDetail as $_applyDetail){
                        list($applyDetailId,$applyDetailNum,$plannedNum) = explode("_",$_applyDetail);
                        $i++;
                        if($i == $count){
                            $_thisPlanNum = $thisPlanNum - $surplus;
                        }else{
                            $maxPlanNum = $applyDetailNum - $plannedNum;
                            $_thisPlanNum = (int)ceil($applyDetailNum / $applyDetailTotal * $thisPlanNum);
                            if($_thisPlanNum > $maxPlanNum){
                                $_thisPlanNum = $maxPlanNum;
                            }
                            $surplus += $_thisPlanNum;
                            if($surplus > $thisPlanNum){
                                $surplus -= $_thisPlanNum;
                                $_thisPlanNum = $thisPlanNum - $surplus;
                                $surplus += $_thisPlanNum;
                            }
                        }
                        if($_thisPlanNum == 0)continue;
                        $data[$supplierId][$pSkuId][$applyDetailId]['plan_num'] = $_thisPlanNum;
                        $data[$supplierId][$pSkuId][$applyDetailId]['apply_num'] = $applyDetailNum;
                    }
                }
            }
            $data[$supplierId][$pSkuId]['plan_num'] = $thisPlanNum;
            $data[$supplierId][$pSkuId]['apply_num'] = $applyDetailTotal;
        }

        if($data){
            //创建采购单
            CreatePurchase::dispatch($data,Admin::user()->id);
        }
        return response()->json(['status' => true, 'message' => '操作成功！']);
    }

}
